﻿using System.Collections.Generic;
using System.Linq;
using Orchard.CultureSwitcher.Models;
using Orchard.Data;
using Orchard.Localization.Services;

namespace Orchard.CultureSwitcher.Services
{
    public class SwitcherSettingsService : ISwitcherSettingsService
    {
        private readonly ICultureManager _cultureManager;
        private readonly IRepository<CulturesOrderRecord> _cultureOrderingRepository;

        public SwitcherSettingsService(ICultureManager cultureManager, IRepository<CulturesOrderRecord> cultureOrderingRepository)
        {
            _cultureManager = cultureManager;
            _cultureOrderingRepository = cultureOrderingRepository;
        }

        public IEnumerable<string> GetOrderedCulturesList()
        {
            var cultures =  _cultureManager.ListCultures();
            return cultures.Select(i =>
            {
                var order = _cultureOrderingRepository.Table.SingleOrDefault(j => j.Culture == i);
                return new
                {
                    Culture = i,
                    OrderNumber = order == null ? 0 : order.OrderNumber
                };
            }).OrderBy(i => i.OrderNumber).Select(i => i.Culture).ToList();
        }

        public void UpdateCultureOrdering(IEnumerable<string> cultures)
        {
            var index = 0;
            foreach (var culture in cultures)
            {
                string lculture = culture;
                var dbitem = _cultureOrderingRepository.Get(i => i.Culture == lculture);

                if (dbitem == null)
                {
                    dbitem = new CulturesOrderRecord
                    {
                        Culture = culture,
                        OrderNumber = ++index
                    };
                    _cultureOrderingRepository.Create(dbitem);
                }
                else
                {
                    dbitem.OrderNumber = ++index;
                    _cultureOrderingRepository.Update(dbitem);
                }
            }
        }
    }
}